from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, DestroyModelMixin
from user import models
from system.serializer.user import UserCRUDSerializer, UserUpdateSerializer, UserCenterSerializer, \
    UserCenterEmailSerializer, UserUpdateInfoCentSerializer, UserCenterUpdateAvater
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from admin.lib.send_sms import send_sms
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView


class UserCRUDView(GenericViewSet, CreateModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = models.UserInfo.objects.filter(is_delete=False).order_by('id')
    serializer_class = UserCRUDSerializer
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object(request)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_del_object(request)
        for i in instance:
            self.perform_destroy(i)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def get_del_object(self, request):      # 单个删除或批量删除
        id_list = request.data
        user_list = []
        for id in id_list:
            user_list.append(models.UserInfo.objects.filter(pk=id))
        return user_list

    def perform_destroy(self, instance):
        instance.update(is_delete=True)



    def get_object(self, request):
        request_id = request.data.get('id')
        return models.UserInfo.objects.filter(pk=request_id).first()

    def get_serializer_class(self):
        if self.action == 'create':
            return UserCRUDSerializer
        elif self.action == 'update':
            return UserUpdateSerializer


class UserCenterPasswordView(GenericViewSet, CreateModelMixin):
    queryset = models.UserInfo.objects.filter(is_delete=False).order_by('id')
    serializer_class = UserCenterSerializer
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

class UserCenterEmailPssword(ModelViewSet):
    queryset = models.UserInfo.objects.filter(is_delete=False).order_by('id')
    serializer_class = UserCenterEmailSerializer

    @action(methods=['POST', ], detail=False, url_path='code/resetEmail')
    def sen_sms(self, request):
        conn = get_redis_connection('code')
        email = request.GET.get('email')
        mail = send_sms.Mail(email)
        code = mail.get_code()
        if mail.send(code):
            conn.set(f'_%s_user_email_code'%request.user, code)
            conn.expire(f'_%s_user_email_code'%request.user, 300)
            return Response('发送成功')
        else:
            return Response('发送失败')

    @action(methods=['POST', ], detail=False, url_path='users/updateEmail')
    def update_email(self, request):
        if type(request.GET.get('code')) != list:
            assert 'code不是一个可迭代对象'
        code = request.GET.get('code')
        conn = get_redis_connection('code')
        redis_code = conn.get(f'_%s_user_email_code'%request.user)
        if not redis_code:
            raise Exception('验证码已过期')
        if code == redis_code.decode('utf-8'):
            instance = self.get_object(request)
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            return Response(serializer.data)
        else:
            raise Exception('验证码错误')
    def get_object(self, request):
        return models.UserInfo.objects.filter(pk=request.user.pk).first()


class UserCenterUpdateInfoView(GenericAPIView, UpdateModelMixin):
    queryset = models.UserInfo.objects.filter(is_delete=False).order_by('id')
    serializer_class = UserUpdateInfoCentSerializer

    def put(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object(request)
        serializer = self.get_serializer(instance, data=request.data, partial=partial, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)

    def get_object(self, request):
        return models.UserInfo.objects.filter(pk=request.user.pk).first()


class UserCenterUpdateAvaterView(GenericAPIView, CreateModelMixin):
    queryset = models.UserInfo.objects.filter(is_delete=False).order_by('id')
    serializer_class = UserCenterUpdateAvater

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.data, status=status.HTTP_201_CREATED)